﻿-- =============================================
-- Author:		M.A.
-- Create date: 05.08.2013
-- Description:	Inserts a new driver record
-- =============================================
CREATE PROCEDURE [trUser].[sp_Drivers_INSERT_NewDriver] 
	@DriverName nvarchar(255),
	@DriverEmail nvarchar(50) = NULL,
	@DriverTelephone nvarchar(50) = NULL
	
	-- Add the parameters for the stored procedure here
AS
BEGIN
	BEGIN TRANSACTION
		BEGIN TRY
			
			DECLARE @New_IDUser bigint 
			DECLARE @New_IDDriver bigint 
	 	
			-- Insert the User, then get the newly created identity
			INSERT INTO tblUsers(Name, Email, Telephone, DateUpdated)
				VALUES (@DriverName, @DriverEmail, @DriverTelephone, GETDATE())
				
			-- the new Identity
			SELECT @New_IDUser = @@IDENTITY
				
			-- create the new driver
			INSERT INTO tblDrivers(IDUser, DateUpdated)
				VALUES (@New_IDUser, GETDATE())
				
			-- get the new driver ID
			SELECT @New_IDDriver = @@IDENTITY
				
			-- return the new Id and the error (0) info
			SELECT 
				@New_IDDriver AS IDDriver
				,@New_IDUser as IDUser
				,0 AS ErrorNumber
				,'' AS ErrorMessage; 
				
		END TRY
		BEGIN CATCH		-- Error happens
				SELECT 
					-1 AS IDDriver
					,- 1 as IDUser
					,ERROR_NUMBER() AS ErrorNumber
					,ERROR_MESSAGE() AS ErrorMessage;
		
			-- rollback transaction
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION;
				
		END CATCH;
		
	-- commit transaction	
	IF @@TRANCOUNT > 0
		COMMIT TRANSACTION;						
END

-- TEST HERE
	/* 
		EXEC [sp_Drivers_INSERT_NewDriver]
			@DriverName='Mesmin Augustin',
			@DriverEmail='mesmin@gmail.com',
			@DriverTelephone='3054943162
	*/